/**
 * 数据看板页面逻辑
 *
 * @author AI Crawlers Team
 * @date 2025-10-10
 */

// 清理可能存在的旧图表实例
if (typeof dashboard !== 'undefined' && dashboard.charts) {
    try {
        Object.values(dashboard.charts).forEach(chart => {
            if (chart && typeof chart.dispose === 'function') {
                chart.dispose();
            }
        });
    } catch (e) {
        console.log('清理旧看板图表:', e);
    }
}

var dashboard = {
    
    /**
     * 初始化
     */
    init() {
        this.loadStatistics();
        this.loadRecentData();
    },
    
    /**
     * 加载统计数据
     */
    async loadStatistics() {
        try {
            // 加载问句统计
            const questionRes = await questionApi.getList({ page: 1, size: 1 });
            const questionData = questionRes.data;
            $('#totalQuestions').text(questionData.total || 0);
            
            // 加载我方产品统计
            const ourProductRes = await productApi.getList({ page: 1, size: 1, isOurProduct: 1 });
            $('#totalOurProducts').text(ourProductRes.data.total || 0);
            
            // 加载竞品统计
            const competitorRes = await productApi.getList({ page: 1, size: 1, isOurProduct: 0 });
            const competitorData = competitorRes.data;
            $('#totalCompetitors').text(competitorData.total || 0);
            
            // 加载图表数据
            this.loadCharts();
            
        } catch (error) {
            console.error('加载统计数据失败：', error);
        }
    },
    
    /**
     * 加载图表
     */
    async loadCharts() {
        this.renderQuestionCategoryChart();
        this.renderProductCategoryChart();
    },
    
    /**
     * 渲染问句类别饼图
     */
    async renderQuestionCategoryChart() {
        try {
            // 获取所有问句
            const res = await questionApi.getList({ page: 1, size: 1000 });
            const questions = res.data.list || [];
            
            // 统计各类别数量
            const categoryCount = {};
            questions.forEach(q => {
                const category = q.category || '未分类';
                categoryCount[category] = (categoryCount[category] || 0) + 1;
            });
            
            // 转换为图表数据
            const chartData = Object.keys(categoryCount).map(key => ({
                name: key,
                value: categoryCount[key]
            }));
            
            // 渲染饼图
            const chart = echarts.init(document.getElementById('questionCategoryChart'));
            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left'
                },
                series: [{
                    name: '问句类别',
                    type: 'pie',
                    radius: '60%',
                    data: chartData,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }]
            };
            chart.setOption(option);
            
        } catch (error) {
            console.error('加载问句类别图表失败：', error);
        }
    },
    
    /**
     * 渲染产品类别柱状图
     */
    async renderProductCategoryChart() {
        try {
            // 获取所有产品
            const res = await productApi.getList({ page: 1, size: 1000 });
            const products = res.data.list || [];
            
            // 统计各类别的我方产品和竞品数量
            const categoryStats = {};
            products.forEach(p => {
                const category = p.category || '未分类';
                if (!categoryStats[category]) {
                    categoryStats[category] = { our: 0, competitor: 0 };
                }
                if (p.isOurProduct === 1) {
                    categoryStats[category].our++;
                } else {
                    categoryStats[category].competitor++;
                }
            });
            
            // 转换为图表数据
            const categories = Object.keys(categoryStats);
            const ourData = categories.map(c => categoryStats[c].our);
            const competitorData = categories.map(c => categoryStats[c].competitor);
            
            // 渲染柱状图
            const chart = echarts.init(document.getElementById('productCategoryChart'));
            const option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                legend: {
                    data: ['我方产品', '竞品']
                },
                xAxis: {
                    type: 'category',
                    data: categories
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '我方产品',
                        type: 'bar',
                        data: ourData,
                        itemStyle: { color: '#28a745' }
                    },
                    {
                        name: '竞品',
                        type: 'bar',
                        data: competitorData,
                        itemStyle: { color: '#ffc107' }
                    }
                ]
            };
            chart.setOption(option);
            
        } catch (error) {
            console.error('加载产品类别图表失败：', error);
        }
    },
    
    /**
     * 加载最近数据
     */
    async loadRecentData() {
        this.loadRecentQuestions();
        this.loadRecentProducts();
    },
    
    /**
     * 加载最近问句
     */
    async loadRecentQuestions() {
        try {
            const res = await questionApi.getList({ page: 1, size: 5 });
            const questions = res.data.list || [];
            
            const container = $('#recentQuestions');
            container.empty();
            
            if (questions.length === 0) {
                container.html('<div class="text-center text-muted py-3">暂无数据</div>');
                return;
            }
            
            questions.forEach(q => {
                const item = $(`
                    <div class="list-group-item list-group-item-action">
                        <div class="d-flex justify-content-between">
                            <div class="flex-grow-1">
                                <p class="mb-1">${utils.escapeHtml(q.questionContent)}</p>
                                <small class="text-muted">
                                    ${q.category ? '<span class="badge bg-info me-1">' + q.category + '</span>' : ''}
                                    ${utils.formatDate(q.createTime, 'YYYY-MM-DD')}
                                </small>
                            </div>
                            <div>
                                <span class="badge bg-${utils.getPriorityClass(q.priority)}">${q.priority}</span>
                            </div>
                        </div>
                    </div>
                `);
                container.append(item);
            });
            
        } catch (error) {
            console.error('加载最近问句失败：', error);
            $('#recentQuestions').html('<div class="alert alert-danger">加载失败</div>');
        }
    },
    
    /**
     * 加载最近产品
     */
    async loadRecentProducts() {
        try {
            const res = await productApi.getList({ page: 1, size: 5 });
            const products = res.data.list || [];
            
            const container = $('#recentProducts');
            container.empty();
            
            if (products.length === 0) {
                container.html('<div class="text-center text-muted py-3">暂无数据</div>');
                return;
            }
            
            products.forEach(p => {
                const item = $(`
                    <div class="list-group-item list-group-item-action">
                        <div class="d-flex justify-content-between">
                            <div class="flex-grow-1">
                                <h6 class="mb-1">${utils.escapeHtml(p.productName)}</h6>
                                <small class="text-muted">
                                    ${p.brand ? p.brand + ' · ' : ''}
                                    ${p.category || ''}
                                    ${p.priceRange ? ' · ' + p.priceRange : ''}
                                </small>
                            </div>
                            <div>
                                ${p.isOurProduct === 1 
                                    ? '<span class="badge bg-success">我方</span>' 
                                    : '<span class="badge bg-warning">竞品</span>'}
                            </div>
                        </div>
                    </div>
                `);
                container.append(item);
            });
            
        } catch (error) {
            console.error('加载最近产品失败：', error);
            $('#recentProducts').html('<div class="alert alert-danger">加载失败</div>');
        }
    }
};

// 页面加载完成后初始化
$(document).ready(function() {
    // 清理可能存在的旧图表实例
    if (dashboard.charts) {
        Object.values(dashboard.charts).forEach(chart => {
            if (chart && typeof chart.dispose === 'function') {
                try {
                    chart.dispose();
                } catch (e) {
                    console.log('销毁旧图表:', e);
                }
            }
        });
        dashboard.charts = {};
    }
    dashboard.init();
});

